from fastapi import FastAPI, Depends
from fastapi_pagination import add_pagination
from common.get_redis import RedisUtil


def configure_event(app: FastAPI):
    """配置事件处理, 并初始化三方库"""

    @app.on_event("startup")
    async def startup_event():
        print("项目启动成功")
        app.state.redis = await RedisUtil.create_redis_pool()
        await app.state.redis.set("test",1111)
        # logger.info("base-api开始启动")
        # 加载数据 redis 基础数据读入内容
        # logger.info("Dash-FastAPI启动成功")

    @app.on_event("shutdown")
    async def shutdown_event():
        print("close")

# 路由设置
def configure_router(app: FastAPI, prefix='/api'):
    """配置后台路由"""
    from module_sys.routers import test
    from common.verify import verify_token
    # 后台依赖
    admin_deps = [Depends(verify_token)]
    # test
    app.include_router(test.router, prefix=prefix, dependencies=admin_deps)


def configure_middleware(app: FastAPI):
    """配置中间件"""
    from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
    from common.middlewares import init_cors_middleware, init_timeout_middleware

    app.add_middleware(ProxyHeadersMiddleware)
    init_cors_middleware(app)
    init_timeout_middleware(app)


def create_app() -> FastAPI:
    """创建FastAPI后台应用,并初始化"""
    from exceptions.global_exc import configure_exception
    app = FastAPI(
        title='base-api',
        description='base-api接口文档',
        version='1.0.0',
    )
    configure_exception(app)
    configure_router(app)
    configure_event(app)
    configure_middleware(app)
    add_pagination(app)
    return app
